<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { sendcmdApi } from "@/api/products/device";
import { ElMessage, ElMessageBox } from 'element-plus';
import DeviceStateLog from './deviceStateLog.vue';
import DeviceAstLog from './deviceAstLog.vue';
import { computed, ref, watch } from "vue";
import { IsBelongAe, IsBelongVI } from "@/utils/appCommon/appCommonOptions/products";
import { mergeObjectsByField } from "@/utils/appCommon/arrayUtil";

const props = defineProps<{
  deviceNo: string;
  params: any;   //查询框参数
}>();

// 按钮loading状态
const loading = ref(false);
// 上次点击时间，用于防抖
const lastClickTime = ref(0);
const showStateLog = ref(false);
const showAstLog = ref(false);
// 防抖时间间隔（毫秒）
const DEBOUNCE_INTERVAL = 1000;

const { t } = useI18n();

// 命令执行函数
const executeCommand = (command: string | number) => {
  // 特殊处理状态日志按钮
  if (command === 'viewStateLog') {
    showStateLog.value = true;
    return;
  }
  
  // 特殊处理AST日志按钮
  if (command === 'viewAstLog') {
    showAstLog.value = true;
    return;
  }
  
  const now = Date.now();

  // 检查是否在防抖时间内
  if (now - lastClickTime.value < DEBOUNCE_INTERVAL) {
    ElMessage.warning(t('device.commands.tooFrequent', { seconds: DEBOUNCE_INTERVAL / 1000 }));
    return;
  }

  // 更新最后点击时间
  lastClickTime.value = now;

  // 设置loading状态
  loading.value = true;

  // 调用后端接口
  sendcmdApi({ deviceNo: props.deviceNo, cmd: command })
    .then((response: any) => {
      ElMessage.success(t('device.commands.success'));
      console.log('命令执行成功:', response);
    })
    .catch((error: any) => {
      ElMessage.error(t('device.commands.failed', { error: error.message || '未知错误' }));
      console.error('命令执行失败:', error);
    })
    .finally(() => {
      // 确保在1秒后才移除loading状态，保证按钮至少1秒内不能再次点击
      setTimeout(() => {
        loading.value = false;
      }, DEBOUNCE_INTERVAL);
    });
};

const CommandList = computed(() => {
  let res = [
    {cmd:0, name:t('device.commands.refreshConfig'),clickFunc:executeCommand},
    {cmd:4, name:t('device.commands.restartDevice'),clickFunc:executeCommand},
    {cmd: 'viewStateLog', name:t('device.commands.stateLogs'),clickFunc:executeCommand},
  ]
  if (IsBelongAe(props.params.productKey)) {
    const tmp =  [
      {cmd:0, name:t('device.commands.refreshConfig'),clickFunc:executeCommand},
      {cmd:4, name:t('device.commands.restartDevice'),clickFunc:executeCommand},
      {cmd:7, name:t('device.commands.checkStatus'),clickFunc:executeCommand},
      {cmd:6, name:t('device.commands.astTest'),clickFunc:executeCommand},
      {cmd: 'viewAstLog', name:t('device.astLogs.viewAstLogs'),clickFunc:executeCommand},
    ]
    res.push(...tmp)
  }
  if (IsBelongVI(props.params.productKey)) {
    const tmp =  [
      {cmd:0, name:t('device.commands.refreshConfig'),clickFunc:executeCommand},
      {cmd:4, name:t('device.commands.restartDevice'),clickFunc:executeCommand},
      {cmd:7, name:t('device.commands.checkStatus'),clickFunc:executeCommand},
    ]
  }
  res = mergeObjectsByField(res,"cmd")
  return res
})

watch(()=>props,(newVal)=>{

},{deep:true,immediate:true})

</script>

<template>
  <div class="ae-commands-container">
    <div class="commands-header">
        <h4>{{ t('device.commands.header', { deviceNo: deviceNo, productKey: params.productKey }) }}</h4>
      </div>

    <div class="commands-grid">
        <el-button
          v-for="(o,index) in CommandList" :key="index"
          type="primary"
          size="small"
          @click="o.clickFunc(o.cmd)"
          class="command-btn"
          :loading="loading"
        >
          {{o.name}}
        </el-button>
    </div>
  </div>
  
  <DeviceStateLog
        :device-no="props.deviceNo"
        v-model:visible="showStateLog"
      />
      
      <DeviceAstLog
        :device-no="props.deviceNo"
        v-model:visible="showAstLog"
      />
</template>

<style scoped lang="scss">
.ae-commands-container {
  padding: 10px;
}

.commands-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.commands-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  align-items: stretch;
}

.command-btn {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  box-sizing: border-box;
}
</style>
